package com.ruoyi.classrecords.controller;

import java.text.ParseException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.order.domain.Order;
import com.ruoyi.order.service.IOrderService;
import com.ruoyi.orderdeduct.domain.OrderDeduct;
import com.ruoyi.orderdeduct.service.IOrderDeductService;
import com.ruoyi.scheduling.domain.DzCourseScheduling;
import com.ruoyi.scheduling.service.IDzCourseSchedulingService;
import com.ruoyi.student.domain.DzStudent;
import com.ruoyi.student.service.IDzStudentService;
import com.ruoyi.withholdingfees.domain.WithholdingFees;
import com.ruoyi.withholdingfees.service.IWithholdingFeesService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.classrecords.domain.ClassRecords;
import com.ruoyi.classrecords.service.IClassRecordsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 上课记录Controller
 *
 * @author ruoyi
 * @date 2024-01-15
 */
@RestController
@RequestMapping("/classrecords/classrecords")
public class ClassRecordsController extends BaseController {
    @Autowired
    private IClassRecordsService classRecordsService;

    /**
     * 查询上课记录列表
     */
    @PreAuthorize("@ss.hasPermi('classrecords:classrecords:list')")
    @GetMapping("/list")
    public TableDataInfo list(ClassRecords classRecords) {
        startPage();
        List<ClassRecords> list = classRecordsService.selectClassRecordsList(classRecords);
        return getDataTable(list);
    }

    /**
     * 导出上课记录列表
     */
    @PreAuthorize("@ss.hasPermi('classrecords:classrecords:export')")
    @Log(title = "上课记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ClassRecords classRecords) {
        List<ClassRecords> list = classRecordsService.selectClassRecordsList(classRecords);
        ExcelUtil<ClassRecords> util = new ExcelUtil<ClassRecords>(ClassRecords.class);
        util.exportExcel(response, list, "上课记录数据");
    }

    /**
     * 获取上课记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('classrecords:classrecords:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(classRecordsService.selectClassRecordsById(id));
    }
    @Autowired
    private IDzStudentService dzStudentService;
    /**
     * 新增上课记录
     */
    @PreAuthorize("@ss.hasPermi('classrecords:classrecords:add')")
    @Log(title = "上课记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ClassRecords classRecords) throws ParseException {
        Long scheduleId = classRecords.getScheduleId();
        String studentId = classRecords.getStudentId();

       DzStudent student = dzStudentService.selectDzStudentById(Long.parseLong(studentId));
        if (student!=null) {
            classRecords.setRemainingclasshours( student.getRemainingClassHours());
            ClassRecords classRecords2 =new ClassRecords();
            classRecords2.setScheduleId(scheduleId);
            classRecords2.setStudentId(studentId);
            classRecords2.setStudentId(studentId);

            List<ClassRecords> classRecords1 = classRecordsService.selectClassRecordsList(classRecords2);
            if (classRecords1.size()>0) {
                return error("此课程已包含此学员，请勿重复添加");
            } else {
                //未添加  补充计算
                if (classRecords.getCommunicate_key().equals("1")) {
                    WithholdingFees withholdingFees1 = new WithholdingFees();
                    withholdingFees1.setStudentId(classRecords.getStudentId());
                    withholdingFees1.setNumber(Integer.parseInt(classRecords.getCourseCancellations()));
                    withholdingFees1.setStudentName(classRecords.getStudentName());
                    withholdingFees1.setDeptId(classRecords.getDeptId());
                    withholdingFees1.setCourseId(classRecords.getCourseId());
                    withholdingFees1.setScheduleId(""+classRecords.getScheduleId());
                    withholdingFeesService.insertWithholdingFees(withholdingFees1);
                    int i = classRecordsService.insertClassRecords(classRecords);
                    UPDATESettlement( "0",classRecords.getStudentId());

                    //补充计算
                    return toAjax(i);
                } else {
                    //直接添加

                    return toAjax(classRecordsService.insertClassRecords(classRecords));
                }


            }
        }else{
            return success();
        }


    }


    @Autowired
    public IDzCourseSchedulingService dzCourseSchedulingService;
    @Autowired
    private IWithholdingFeesService withholdingFeesService;

    /**
     * 修改上课记录
     */
    @PreAuthorize("@ss.hasPermi('classrecords:classrecords:edit')")
    @Log(title = "上课记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ClassRecords classRecords) {
        //扣费
        if (classRecords.getStudentId() != null && classRecords.getCourseCancellations() != null) {
            classRecordsService.updateClassRecords(classRecords);
            //没有就新增
            WithholdingFees withholdingFees1 = new WithholdingFees();
            withholdingFees1.setStudentId(classRecords.getStudentId());
            withholdingFees1.setNumber(Integer.parseInt(classRecords.getCourseCancellations()));
            withholdingFees1.setStudentName(classRecords.getStudentName());
            withholdingFees1.setDeptId(classRecords.getDeptId());
            withholdingFees1.setCourseId(classRecords.getCourseId());
            withholdingFees1.setScheduleId(""+classRecords.getScheduleId());
            withholdingFeesService.insertWithholdingFees(withholdingFees1);
            return toAjax(true);
        } else {
            return toAjax(classRecordsService.updateClassRecords(classRecords));
        }


    }

    /**
     * 删除上课记录
     */
    @PreAuthorize("@ss.hasPermi('classrecords:classrecords:remove')")
    @Log(title = "上课记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) throws ParseException {
        for (int i=0; i<ids.length; i++) {
            ClassRecords classRecords = classRecordsService.selectClassRecordsById(ids[i]);
            String settlestatus = classRecords.getSettlestatus();
            if (settlestatus.equals("已结算")) {
                //获取课消数
                 String courseCancellations = classRecords.getCourseCancellations();
                 int intcourseCancellations=Integer.parseInt(courseCancellations);
                 int number=Math.negateExact(intcourseCancellations);
                WithholdingFees withholdingFees1 = new WithholdingFees();
                withholdingFees1.setStudentId(classRecords.getStudentId());
                withholdingFees1.setNumber(number);
                withholdingFees1.setStudentName(classRecords.getStudentName());
                withholdingFees1.setDeptId(classRecords.getDeptId());
                withholdingFees1.setCourseId(classRecords.getCourseId());
                withholdingFees1.setScheduleId(""+classRecords.getScheduleId());
                withholdingFeesService.insertWithholdingFees(withholdingFees1);
                 UPDATESettlement( "" ,classRecords.getStudentId());
            } else {

            }


        }



        return toAjax(classRecordsService.deleteClassRecordsByIds(ids));
    }
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderDeductService orderDeductService;
    String studentId;
    //及时结算 结算一次
    public  void  UPDATESettlement( String type,String  studentIds) throws ParseException {
        WithholdingFees withholdingFees1=new WithholdingFees();
        withholdingFees1.setStudentId(studentIds);
        List<WithholdingFees> WithholdingFeeslist = withholdingFeesService.selectWithholdingFeesList(withholdingFees1);
        for (int i=0; i<WithholdingFeeslist.size(); i++) {
            WithholdingFees withholdingFees = WithholdingFeeslist.get(i);
              studentId =withholdingFees .getStudentId();
            //获取待扣费数量
            int intNumber =withholdingFees .getNumber();

            Order order=new Order();
            order.setStudentId(studentId);
            order.setOrderRemark10(type);

            List<Order> list = orderService.selectOrderList(order);
            //如果有此用户的订单
            if (list.size()>0) {
                Order order1 = list.get(0);
                //获取剩余课程数量
                String residue = order1.getResidue();
                //获取剩余课程数量int
                int intresidue = Integer.parseInt(residue);

                //获取单价
                String unitPrice = order1.getUnitPrice();
                //int单价
                float intunitPrice = Float.parseFloat(unitPrice);
                //获取已消课数量
                String consumed = order1.getConsumed();
                //获取已消课数量
                int intconsumed = Integer.parseInt(consumed);
                //累计已消课数量
                int nowintconsumed=intconsumed+intNumber;
                //设置已消课数量
                order1.setConsumed(""+nowintconsumed);
                //累计已消课金额
                float  consumedmoney= nowintconsumed*intunitPrice;
                //设置已消费金额
                order1.setMoneyDetermined(""+consumedmoney);

                //对订单进行扣费，计算剩余扣费金额
                int nownumer=  intresidue-intNumber;

                //添加订单扣费记录
                OrderDeduct orderDeduct=new OrderDeduct();
                orderDeduct.setOrderId(""+order1.getOrderId());
                orderDeduct.setStudentId(""+order1.getStudentId());
                orderDeduct.setNumber(intNumber);
                orderDeduct.setCourseId(withholdingFees.getCourseId());

                orderDeduct.setScheduleId(""+withholdingFees.getScheduleId());
                orderDeduct.setDeptId(withholdingFees.getDeptId());
                //获取课程信息
                DzCourseScheduling dzCourseScheduling = dzCourseSchedulingService.selectDzCourseSchedulingById(Long.parseLong(withholdingFees.getScheduleId()));
                if (dzCourseScheduling!=null) {
                    orderDeduct.setClassTime(dzCourseScheduling.getStudyDate()+" "+dzCourseScheduling.getClassStart()+"-"+dzCourseScheduling.getClassFinish());

                }


                orderDeductService.insertOrderDeduct(orderDeduct);

                if (nownumer>0) {
                    //够扣费,设置剩余课时
                    order1.setResidue(""+nownumer);


                    //计算未确认收入
                    float unmoney=  nownumer*intunitPrice;
                    //设置未确认收入
                    order1.setMoneyUnconfirmed(""+unmoney);

                    order1.setState("进行中");
                    orderService.updateOrder(order1);
                    //删除待扣费记录
                    withholdingFeesService.deleteWithholdingFeesById(withholdingFees.getId());

                } else {
                    //设置剩余课时
                    order1.setResidue("0");
                    //设置未扣费收入
                    order1.setMoneyUnconfirmed("0" );
                    order1.setState("已完结");
                    order1.setOrderRemark10("1");
                    //不够扣费
                    int positivenownumer = Math.abs(nownumer);
                    withholdingFees.setNumber(positivenownumer);
                    orderService.updateOrder(order1);
                    //更新待扣费
                    withholdingFeesService.updateWithholdingFees(withholdingFees);

                }

                Order orderquery=new Order();
                orderquery.setStudentId(studentId);
                orderquery.setOrderRemark10("0");

                List<Order> Orderlist = orderService.selectOrderList(orderquery);
                int value=0;
                for (int w=0; w<Orderlist.size(); w++) {
                    String residue1 = Orderlist.get(w).getResidue();
                    int intresidue1 = Integer.parseInt(residue1);
                    //剩余课数量
                    value=value+intresidue1;


                }
                //更新用户信息
                DzStudent dzStudent = dzStudentService.selectDzStudentById(Long.parseLong(order.getStudentId()));
                dzStudent.setRemainingClassHours(""+value);
                dzStudentService.updateDzStudent(dzStudent);


                ClassRecords classRecords=new ClassRecords();
                classRecords.setStudentId(order.getStudentId());
                List<ClassRecords> classRecords1 = classRecordsService.selectClassRecordsList(classRecords);
                for (int z=0; z<classRecords1.size(); z++) {

                    classRecords1.get(z).setRemainingclasshours(""+value);
                    classRecords1.get(z).setSettlestatus("已结算");


                    //更新记录中的剩余课时数
                    classRecordsService.updateClassRecords(classRecords1.get(z));



                }
                WithholdingFees withholdingFees2=new WithholdingFees();
                withholdingFees2.setStudentId(studentId);


                List<WithholdingFees> WithholdingFeeslist2 = withholdingFeesService.selectWithholdingFeesList(withholdingFees2);
                if (WithholdingFeeslist2.size()>0) {
//                    UPDATESettlement(   type,studentId);
                }



            } else {

                //无订单，不更新

            }



        }


    }

}
